package com.ux.iot.core.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSON;
import com.ux.iot.core.annotation.MessageHandler;
import com.ux.iot.core.annotation.MessageListener;
import com.ux.iot.core.bo.AmqpData;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * @author caixiaodao
 * @version 1.0
 * 功能描述
 * topic 对应实例管理器
 * @date 2021/12/5 11:42
 */
@Slf4j
@AllArgsConstructor
public  abstract class MessageHandlerManager {
    ApplicationContext applicationContext;

    public abstract String getRoute(String topic);

    /**
     * @return
     */
    public boolean handler(AmqpData data) {
        if (ObjectUtil.isEmpty(data.getTopic())) {
            log.error("topic 为空");
        } else {
               String key = getRoute(data.getTopic());
            // 获取处理类
                try{
                //log.debug("当前所有的bean名称{}",JSON.toJSONString(applicationContext.getBeanDefinitionNames()));
                Object ob = applicationContext.getBean(key);
                log.debug("当前处理bean名称{} 实例类:{}",key,ob!=null?ob.getClass().getSimpleName():"为空");

                MessageListener messageListener = ob.getClass().getAnnotation(MessageListener.class);
                if(key.equals(Base64.encode(messageListener.value()))){
                    Method[] methods= ob.getClass().getMethods();
                    Method handler=null;
                    for(Method method:methods){
                        if(ObjectUtil.isNotEmpty(method.getAnnotation(MessageHandler.class))){
                              handler=method;
                              break;
                        }
                    }
                    if(ObjectUtil.isNotEmpty(handler)){
                       ReflectUtil.invoke(ob,handler.getName(), JSON.toJSONString(data));
                    }
                }

                }catch (Exception e){
                    log.error("消息处理出错{}", e.getMessage());
                }

        }
        return  true;
    }



}
